<?php
namespace Api\Controller;
use Think\Controller;
class QrcodeController extends CommonController {
	private function getAccessToken(){
		$map['wid'] = session("wid");
		$info = M("Wechat")->where($map)->find();

		if(date("Y-m-d H:i:s") < $info['token_end_time']){
            return $info['authorizer_access_token'];
        }else{
            $token = $this->get_component_access_token();
            $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$token}";

            $post_data = array(
                "component_appid"=>C("OPEN_APPID"),
                "authorizer_appid"=>$info['appid'],
                "authorizer_refresh_token"=>$info['authorizer_refresh_token']);
            $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
            $res = $this->ihttp_post($url, $json);
            $td = json_decode($res, true);
            if($td['authorizer_access_token']){
                $map['wid'] = $info['wid'];
                $data['authorizer_access_token'] = $td['authorizer_access_token'];
                $data['authorizer_refresh_token'] = $td['authorizer_refresh_token'];
                $data['token_end_time'] = date("Y-m-d H:i:s", time()+$td['expires_in']-60);
                M("Wechat")->where($map)->save($data);
                return $td['authorizer_access_token'];
            }else{
                // dump($td);
                // $this->error($td['errmsg']);
                // $this->reAuth();
                exit("网络忙！");
            }
        }
	}

	private function get_component_access_token(){
        $token = S("component_access_token");
        if($token){
            return $token;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";

        $post_data = array(
            "component_appid"=>C("OPEN_APPID"),
            "component_appsecret"=>C("OPEN_APPSECRET"),
            "component_verify_ticket"=>S("component_verify_ticket"));
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['component_access_token']){
            S("component_access_token", $td['component_access_token'], $td['expires_in'] - 120);
            return $td['component_access_token'];
        }else{
            return false;
        }
    }

	public function getOrderWxaCode(){
		$access_token = $this->getAccessToken();

		$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
		// dump($url);
		$post_data = array(
			'scene'=>$_GET['out_trade_no'],
			'page'=>'pages/mine/shop/yan/list'
		);
		$json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        header('Content-type: image/JPEG');
        echo $res;
        // dump($res);
	}
}